package sg.edu.nus.iss.vmcs.system;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class XmlPropertyLoaderImpl  implements PropertyLoaderImpl {
	
	private String fileName;
	
	public XmlPropertyLoaderImpl(String fileName) {
		this.fileName = fileName;
	}

	/**
	 * This method reads the properties file into a hash table.
	 * @throws IOException if fail to load properties from properties xml file.
	 */
	public void initialize(Properties prop) throws IOException {
		FileInputStream stream = new FileInputStream(fileName);
		prop.loadFromXML(stream);
		stream.close();
	}
	
	/**
	 * This method writes the properties from the hash table to the xml file after removing the system properties.
	 * @throws IOException if fail to store properties to properties file.
	 */	
	public void saveProperty(Properties prop) throws IOException {
		FileOutputStream stream = new FileOutputStream(fileName);
		Properties customProp = new Properties();
		
		for(Map.Entry<Object, Object> entry : prop.entrySet()) {
			
			String key = entry.getKey().toString();
			
			if (key.startsWith("java.") || key.startsWith("sun.") || key.startsWith("awt.") || key.startsWith("os.") 
					|| key.startsWith("user.") || key.startsWith("file.") || key.startsWith("line.") || key.startsWith("path.")) {
				continue;
			}
			customProp.setProperty(entry.getKey().toString(), entry.getValue().toString());
		}
		
		customProp.storeToXML(stream, "");
		stream.close();
	}
}
